<template>
  <div :id="eId" style="width: 100%; height: 100%"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'LineEchart',
  props: {
    dataSource: {
      type: Object,
      default() {
        return {
          data: [120, 132, 101, 134, 90, 230, 210],
          xAxis: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        }
      }
    },
    color: {
      type: String,
      default() {
        return '#000'
      }
    },
    echatsType: {
      type: String,
      default() {
        return 'line'
      }
    },
    eId: {
      type: String,
      default() {
        return 'main'
      }
    }
  },
  data() {
    return {
      myChart: null
    }
  },
  computed: {},
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.myChart = echarts.init(document.getElementById(this.eId))
      var option = {
        title: {},
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: 5,
          top: 5,
          right: 5,
          bottom: 20
        },
        xAxis: {
          show: false,
          type: 'category',
          boundaryGap: false,
          data: this.dataSource.xAxis
        },
        yAxis: {
          show: false,
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [
          {
            type: this.echatsType,
            data: this.dataSource.data,
            showSymbol: false,
            itemStyle: {
              color: this.color
            },
            markLine: {
              symbol: 'none',
              label: {
                show: true,
                formatter: '平均值',
                color: '#999',
                position: 'insideStartTop'
              },
              lineStyle: {
                color: '#ccc',
                type: 'solid'
              },
              data: [{ type: 'average', name: '平均值' }]
            }
          }
        ]
      }

      option && this.myChart.setOption(option)
      let that = this
      setTimeout(() => {
        that.myChart.resize()
      }, 200)
      window.addEventListener('resize', () => {
        setTimeout(() => {
          that.myChart.resize()
        }, 200)
      })
    }
  },
  watch:{
    dataSource(){
      this.init();
    },
  }
}
</script>